import React, {useContext, useEffect, useState} from "react";
import {Icon, ListItem, Text} from "react-native-elements";
import {
    ActivityIndicator,
    Alert,
    Dimensions,
    ImageBackground,
    RefreshControl,
    TextInput,
    TouchableOpacity,
    View
} from "react-native";
import LocaleContext from "../libs/locale";
import pool_find from "../assets/Pool/pool_find.png";
import {ScrollView} from "react-native-gesture-handler";
import {constansts} from "../libs/constansts";
import sETHlogo from "../assets/1.png";
import susdtlogo from "../assets/susdt.png";
import otherTokenLogo from "../assets/hotTokenLogo.png";
import SmartXLogo from "../assets/NFT/SmartXNFT.png";
import WalletContext from "../libs/wallet";
import NFT from "../assets/Assets/NFT.png";
import {Image} from "react-native-elements/dist/image/Image";
import {Avatar} from "react-native-elements/dist/avatar/Avatar";
import {getTokenName} from "../libs/nodes";
import {getMyAddNFTs, modifyMyAddNFTS, NFTView_IDSize, NFTView_TitleSize} from "../libs/NFTView";

const {width,height,scale} = Dimensions.get("window");

const NFTAddContract = ({navigation}:any) => {
    const locale:any = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);
    const [refresh, setRefresh] = useState(true);
    const [seachTxt,setSeachTxt] = useState('');
    const [NFTList,setNFTList]:any = useState([]);
    const [NFTAddList,setNFTAddList]:any = useState([]);
    const [showSearch,setShowSearch] = useState(false);
    let t:any = null;

    useEffect(()=>{
        let NFTListTemp = [
            {name:"SmartXNFT",contract:"c3MbYezD7CV9KcRZbnoVTmT6SMAzs2REL"}
            ];
        setNFTList(NFTListTemp);

        setMyAddNFTS();
    },[refresh])
    const setMyAddNFTS = async () => {
        let NFTAddListTemp = await getMyAddNFTs(wallet.address);
        setNFTAddList(NFTAddListTemp);
        return NFTAddListTemp;
    }
    const Anti_shake = (value:string) =>{
        console.log(`第一个t=`+t)
        if(t!==null)
        {
            clearTimeout(t);
            console.log(`清理后t=`+t)
        }
        t=setTimeout(()=>{searchEnding(value.trim())},500)//2行代码简单防抖
        console.log(`设置后t=`+t)
        setSeachTxt(value.trim());
    }
    const searchEnding = async (value:string)=>{
        try {
            if(value=="")
            {
                return ;
            }
            let tokenName;
            try{
                tokenName = await getTokenName(value);
            }catch (e) {
                setNFTList([]);
                setShowSearch(false);
                return ;
            }

            console.log("tokenName="+tokenName);
            // var searchToken = {address:seachTxt,uri:"",desc:tokenName};
            var searchToken = [{contract:value,name:tokenName}];
            setNFTList((searchToken as any));
            setShowSearch(true);
            // setSeachTxt('');
        } catch (e) {
            console.log('searchEnding==>', e);
            setSeachTxt('');
        }
    };
    const addNFTContract = async (item:any) => {
        let addNFTListTemp = await setMyAddNFTS();
        let index = addNFTListTemp.findIndex((res:any)=>item.contract===res.contract);
        console.log(index)
        console.log(item)
        if(index>=0)
        {
            await modifyMyAddNFTS(wallet.address,item.contract,"remove",item.name);
            await setMyAddNFTS();
            return ;
        }
        await modifyMyAddNFTS(wallet.address,item.contract,"add",item.name);
        await setMyAddNFTS();
    }

    return (
        <View>
            <View style={{flexDirection:"row",justifyContent:"space-between",marginLeft:20,alignItems:"center"}}>
                <View style={{justifyContent:"center",height:30,flex:1,flexDirection:"row",backgroundColor:"#E7E7E8",borderRadius:20,marginTop:10}}>
                    <ImageBackground
                        source={pool_find}
                        style={{ width: 20, height:20, marginLeft:10,paddingRight:35,alignSelf:'center' }} />
                    <TextInput
                        underlineColorAndroid={'transparent'}
                        placeholder= {locale?._('Token.tokenSearch')}
                        defaultValue={seachTxt}
                        onChangeText={
                            (value) => {
                                //搜索合约问题后面解决,搜索的时候需要去合约全局搜索
                                Anti_shake(value)
                            }
                        }
                        style={{
                            flex:1,
                            padding:0,
                            paddingRight:20,
                            fontSize:13
                        }
                        }
                    />
                </View>
                <TouchableOpacity
                    style={{height:30,marginTop:10,marginRight:20,width:50,alignItems:"center",justifyContent:"flex-end",flexDirection:"row"}}
                    activeOpacity={1} onPress={()=>{
                    navigation.goBack();
                }}>
                    <Text style={{fontSize:13,textAlignVertical:"center",textAlign:"center"}}>{locale._("NFT_Add_Cancle")}</Text>
                </TouchableOpacity>
                {/*<Text style={{marginLeft:"2%",alignSelf:"center",fontWeight:"bold"}}>取消</Text>*/}
            </View>
            {
                !showSearch?<Text style={{marginTop:15,marginLeft:20,fontWeight:"bold",fontSize:NFTView_TitleSize}}>{locale._("NFT_Add_Hot")}</Text>:null
            }
            <ScrollView refreshControl={
                <RefreshControl refreshing={false} onRefresh={() => setRefresh(true)} collapsable={true} />}
            >
                <View style={{padding:5}}>
                    {
                        NFTList.length
                            ?
                            NFTList.map((tx: any,index:any) => (
                                <ListItem
                                    bottomDivider onPress={async ()=>{
                                    await addNFTContract(tx);
                                }} activeOpacity={1} key={index}>
                                    {
                                        tx.contract==="c3MbYezD7CV9KcRZbnoVTmT6SMAzs2REL"?
                                            <Avatar source={SmartXLogo} rounded={true} activeOpacity={0.7}/>
                                            :
                                            <Avatar title={tx.name.slice(0,2)} titleStyle={{color:"#fff"}} containerStyle={{backgroundColor:"lightgrey"}} rounded={true} activeOpacity={0.7}/>
                                    }

                                    <ListItem.Content>
                                        <ListItem.Title style={{fontSize:NFTView_TitleSize}}>{tx.name}</ListItem.Title>
                                        <ListItem.Subtitle style={{fontSize:NFTView_IDSize}}>{tx.contract.slice(0,9)+"..."+tx.contract.slice(-10)}</ListItem.Subtitle>
                                    </ListItem.Content>
                                    {
                                        (NFTAddList).findIndex((item:any)=>item.contract===tx.contract)!==-1?
                                            <Icon type='feather' name='minus-circle' color='#7259E0FF' size={24}  />
                                            :
                                            <Icon type='feather' name='plus-circle' color='#7259E0FF' size={24} />
                                    }
                                </ListItem>
                            ))
                            :
                            <View style={{ flex: 1, justifyContent: 'center',backgroundColor:"#fff" }}>
                                <Image
                                    style={{width:width-30,height:300}}
                                    source={NFT}/>
                            </View>
                    }

                </View>
            </ScrollView>
        </View>
    )
}

export default NFTAddContract;


